package com.gcy.wanandroid.ui.activity.main;

import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;

import com.gcy.wanandroid.R;
import com.gcy.wanandroid.base.BaseActivity;
import com.gcy.wanandroid.config.Constants;
import com.gcy.wanandroid.databinding.ActivityMainBinding;
import com.gcy.wanandroid.navinterface.ScrollToTop;
import com.gcy.wanandroid.ui.activity.login.LoginActivity;
import com.gcy.wanandroid.ui.view.CircleImageView;
import com.gcy.wanandroid.util.GlideUtil;
import com.google.android.material.bottomnavigation.BottomNavigationView;

import org.w3c.dom.Text;

public class MainActivity extends BaseActivity<ActivityMainBinding, MainViewModel> {

    private boolean isLogin;
    private DrawerLayout drawer;
    private AppBarConfiguration mConfiguration;

    public static void start(Context context, Boolean isLogin) {
        Intent intent = new Intent(context, MainActivity.class);
        intent.putExtra(Constants.ParamCode.PARAM1, isLogin);
        context.startActivity(intent);
    }

    @Override
    protected void handleIntent(Intent intent) {
        isLogin = intent.getBooleanExtra(Constants.ParamCode.PARAM1, false);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        isLogin = intent.getBooleanExtra(Constants.ParamCode.PARAM1, false);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mViewModel.getUserData();
    }

    @Override
    protected void onResume() {
        super.onResume();
        login();
    }

    @Override
    protected void init() {
        initView();
        initUserData();
        initFloatingActionButton();
    }


    @Override
    protected void bindViewModel() {
        mDataBinding.setViewModel(mViewModel);
    }

    @Override
    protected void initViewModel() {
        mViewModel = new ViewModelProvider(this).get(MainViewModel.class);
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_main;
    }

    /**
     * @author gcy
     * @description 初始化侧边栏和底部状态栏
     * @date 2023/5/23 15:14
     */
    private void initView() {
        setSupportActionBar(mDataBinding.toolbar);
        drawer = mDataBinding.drawerLayout;

        mConfiguration = new AppBarConfiguration.Builder(R.id.nav_home, R.id.nav_square, R.id.nav_about, R.id.nav_update)
                .setDrawerLayout(drawer)
                .build();
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
        NavigationUI.setupActionBarWithNavController(this, navController, mConfiguration);
        NavigationUI.setupWithNavController(mDataBinding.navView, navController);
        BottomNavigationView navView = findViewById(R.id.nav_view_bottom);
        NavigationUI.setupWithNavController(navView, navController);
    }

    /**
     * @author gcy
     * @description 初始化侧边栏用户信息
     * @date 2023/5/29 19:39
     */
    private void initUserData() {
        TextView tvName = mDataBinding.navView.getHeaderView(0).findViewById(R.id.tv_nike_name);
        TextView textView = mDataBinding.navView.getHeaderView(0).findViewById(R.id.textView);
        CircleImageView ivHeader = mDataBinding.navView.getHeaderView(0).findViewById(R.id.imageView);
        //加载用户昵称和账号
        mViewModel.getUserBean().observe(this, loginBean -> {
            if (loginBean != null) {
                tvName.setText(loginBean.getNickname());
                textView.setText(loginBean.getUsername());
            } else {
                tvName.setText(getResources().getString(R.string.user_name));
                textView.setText(getResources().getString(R.string.click_login));
            }
        });
        //加载用户头像
        mViewModel.getUserHeader().observe(this, url -> {
            GlideUtil.loadImageWithDefault(ivHeader, url);
        });
        //点击头部个人信息
        mDataBinding.navView.getHeaderView(0).setOnClickListener(v -> {
            if (mViewModel.getUserBean().getValue() == null) {
                //跳转登录页面
                LoginActivity.start(MainActivity.this);
                drawer.closeDrawer(GravityCompat.START);
            } else {
                //跳转到mine页面
                Navigation.findNavController(MainActivity.this, R.id.nav_host_fragment).navigate(R.id.mineFragment);
                drawer.closeDrawer(GravityCompat.START);
            }
        });
    }

    /**
     * @author gcy
     * @description FloatingActionButton点击事件，回到顶部
     * @date 2023/5/31 18:29
     */
    private void initFloatingActionButton() {
        mDataBinding.fabTop.setOnClickListener(v -> {
            Fragment fragment = getFragment();
            if (fragment != null) {
                ((ScrollToTop) fragment).scrollToTop();
            }
        });
    }

    /**
     * 获取当前显示的Fragment实例
     */
    private Fragment getFragment() {
        //获取指定的fragment
        Fragment mMainNavFragment = getSupportFragmentManager().findFragmentById(R.id.nav_host_fragment);
        Fragment fragment = mMainNavFragment.getChildFragmentManager().getPrimaryNavigationFragment();
        if (fragment instanceof ScrollToTop) {
            return fragment;
        }
        return null;
    }

    //处理导航栏（AppBar）中的后退操作

    @Override
    public boolean onSupportNavigateUp() {
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
        return NavigationUI.navigateUp(navController, mConfiguration) || super.onSupportNavigateUp();
    }

    @Override
    public void onBackPressed() {
        if (drawer == null) {
            return;
        }
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    private void login() {
        if (isLogin) {
            //已经登录成功，直接从缓存中获取用户信息
            mViewModel.setUserBean();
        }
    }
}